<?php
/**
 * Created by PhpStorm.
 * User: sunfan
 * Date: 2017/3/9
 * Time: 17:06
 */

namespace Clientapi\Controller;


class WxLoginController extends MapiBaseController
{
    public function login()
    {
        $data = $this->data;
        $code = $data['code'];
        $code = "021JE9842k1uxJ0Q9X742H1L742JE98X";
//        $state = $data['state'];
        $appid = C('WxAppPayConf_pub.APPID');
        $secret = C('WxAppPayConf_pub.APPSECRET');
        $token_url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid={$appid}&secret={$secret}&code={$code}&grant_type=authorization_code";

        $token_res = file_get_contents($token_url);
        $token_res = json_decode($token_res,true);

//        $this->ApiReturn(0, '成功', $token_res);

        if($token_res['errcode']){
            file_put_contents('/Public/wei_log.logs',json_encode($token_res,JSON_UNESCAPED_UNICODE),FILE_APPEND);
            $this->ApiReturn(-1,'获取token失败');
        }
        file_put_contents('/Public/wei.logs',json_encode($token_res,JSON_UNESCAPED_UNICODE));
        $user_url = "https://api.weixin.qq.com/sns/userinfo?access_token={$token_res['access_token']}&openid={$token_res['openid']}";

        $user_res = file_get_contents($user_url);
        $user_res = json_decode($user_res,true);

        $this->ApiReturn(0, '', $user_res);

        if($user_res['errcode']){
            file_put_contents('/Public/wei_log.logs',json_encode($user_res,JSON_UNESCAPED_UNICODE),FILE_APPEND);
            $this->ApiReturn(-1, '获取用户信息失败');
        }

        $users = M('user');
        $count = $users->where(array('openid'=>$user_res['openid']))->count();
        if($count == 0){
            $user_data['register_time'] = time(); //注册时间
            $user_data['last_login_time'] = time();
            $user_data['last_login_ip'] = $_SERVER['REMOTE_ADDR'];

            $user_data['image'] = $this->getimg($user_res['headimgurl']);

            $user_data['sex'] = $user_res['sex'];
            $user_data['name'] = $user_res['nickname'];
            $uok = $users->add($user_data);
            if($uok){
                $user = $users->where(array('user_id'=>$uok))->find();

                $this->ApiReturn(0, '登陆成功', $user);
            }else{
                $this->ApiReturn(-1, '登陆失败');
            }
        }else{

            $user = $users->where(array('openid'=>$user_res['openid']))->find();
            $this->ApiReturn(0, '登陆成功', $user);

        }

    }

    protected function getExtend(){
        $extend = substr(str_shuffle(time().mt_rand(1000000,9999999)),0,7);
        $row = D('user')->where(array('extend'=>$extend))->count();
        while($row != 0){
            $extend = substr(str_shuffle(time().mt_rand(1000000,9999999)),0,7);
            $row = D('user')->where(array('extend'=>$extend))->count();
        }
        return $extend;
    }

    public function getimg($url){

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        $output = curl_exec($ch);
        curl_close($ch);
        $img_name = time().mt_rand(1000000,9999999).'.png';
        $root_path = C('WEI_IMG');
        $sub_path = '/Public/uploads/log/weilog/';
        if(!file_exists($root_path.$sub_path)){
            mkdir($root_path.$sub_path,0777,true);
        }

        $ok = file_put_contents($root_path.$sub_path.$img_name,$output);
        if($ok){
            return $sub_path.$img_name;
        }else{
            return '/Public/uploads/log/timg.jpg';
        }

    }

}